import logging
import os
from logging import handlers


class Loggers:
    def make_logger(self, file_name):
        logger = logging.getLogger('xue') # 获取logger对象
        logger.setLevel(logging.DEBUG)   # 设置logger的level为debug
        # 实例化logger的得到处理器handle模板
        console = logging.StreamHandler()  # StreamHandler()控制台输出
        # 将日志输入到log下
        log_path = os.path.abspath(os.path.dirname(__file__) + os.path.sep+"..")
        file = handlers.TimedRotatingFileHandler(filename='{}/log/{}.log'.format(log_path, file_name), when='D',
                                             backupCount=1, encoding='utf-8')   # 日志每隔一天重新生成一个新的日志
        # 日志输出方式
        formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
        # 将输出方式方式加载到handle
        console.setFormatter(formatter)
        file.setFormatter(formatter)
        # 将处理器添加到logger,让句柄唯一,如果不唯一的话,就会出现重复值
        if len(logger.handlers) == 0:
            logger.addHandler(console)
            logger.addHandler(file)
        logger.removeHandler(console)
        logger.removeFilter(file)

        return logger


if __name__ == '__main__':
    for i in range(5):
        logger = Loggers().make_logger('test')
        logger.info('testsss')

